﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using xxpl.Utils;

namespace xxpl.GAE
{
    public class RequestContext
    {
        private readonly WebHeaderCollection headerCollection;
        private readonly byte[] postData;
        private readonly HttpListenerRequest request;
        private readonly DateTime requestStartDate;

        protected RequestContext(HttpListenerRequest request)
        {
            this.request = request;

            requestStartDate = DateTime.Now;

            postData = new byte[request.ContentLength64];

            using (Stream st = request.InputStream)
            {
                int count = 0;
                while (count < request.ContentLength64)
                {
                    int result = st.Read(postData, 0, postData.Length);
                    if (result == 0) break;
                    count += result;
                }
                st.Close();
            }

            headerCollection = new WebHeaderCollection();

            foreach (string header in request.Headers.AllKeys.Where(Guard.IsSafeHeader))
            {
                if ("range".Equals(header, StringComparison.CurrentCultureIgnoreCase)) OrignalRangeSpecified = true;
                headerCollection.Add(header, request.Headers[header]);
            }
        }

        public byte[] PostData
        {
            get { return postData; }
        }

        public WebHeaderCollection HeaderCollection
        {
            get { return headerCollection; }
        }

        public string HttpMethod
        {
            get { return request.HttpMethod; }
        }

        public string RawUrl
        {
            get { return request.RawUrl; }
        }

        public string Host
        {
            get { return request.Url.Host; }
        }

        public EndPoint RemoteEndPoint
        {
            get { return request.RemoteEndPoint; }
        }

        public int? RangeStart { get; set; }

        public bool OrignalRangeSpecified { get; set; }

        public int? TotalRange { get; set; }

        public DateTime RequestStartDate
        {
            get { return requestStartDate; }
        }

        public static RequestContext Create(HttpListenerRequest request)
        {
            return new RequestContext(request);
        }
    }
}